package com.gszy.auth.mvc;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author MeUChT
 */
public class MethodUtils {
    /**
     * 根据包名获取当前包下所有被@RequestMapping修饰的方法Method对象
     * 然后获取当前方法的映射路径 将路径作为key和方法作为value保存在MethodMap
     * @param packageName 包名
     * @return
     */
    public static Map<String, Method> getMethodMap(String packageName){

        Map<String,Method> methodMap = new HashMap<>();

        Set<Class<?>> controllerClass = ClassUtils.getControllerClass(packageName);

        for (Class<?> clazz : controllerClass){
            //key - value
            //key @Controller 保存于前缀@RequestMapping 保存了剩下的映射
            Controller controllerAnno = clazz.getAnnotation(Controller.class);
            String preUrl = controllerAnno.value();
            //获取当前类对象中所有的方法
            Method[] methods = clazz.getMethods();
            for (Method method : methods){
                //筛选出@RequestMapping修饰的方法
                if (method.isAnnotationPresent(RequestMapping.class)){
                    //key (前缀 + url)-value
                    RequestMapping requestMappingAnno = method.getAnnotation(RequestMapping.class);
                    String url = preUrl + requestMappingAnno.value();

                    methodMap.put(url,method);

                }
            }
        }
        return methodMap;
    }
}
